package com.song.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.song.mapper.EmpExprMapper;
import com.song.mapper.EmpMapper;
import com.song.pojo.Emp;
import com.song.pojo.EmpQueryParam;
import com.song.pojo.PageResult;
import com.song.service.EmpExprService;
import com.song.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Override
    public PageResult<Emp> getEmps(EmpQueryParam  param) {
        //1.设置分页参数
        PageHelper.startPage(param.getPage(),param.getPageSize());
        //2，查询结果集
        List<Emp> emps = empMapper.getEmps(param);
        //3.解析查询结果集,并封装
        Page<Emp> p = (Page<Emp>) emps;
        return new PageResult<Emp>(p.getTotal(), p.getResult());
    }
    @Transactional
    @Override
    public Integer addEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        Integer res = empMapper.addEmp(emp);

        if(!CollectionUtils.isEmpty(emp.getExprList())){
            emp.getExprList().forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.addEmpExpr(emp.getExprList());
        }
        return res;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteEmp(List<Integer> ids) {
        //批量删除员工工作经历
        empExprMapper.deleteEmpExpr(ids);
        //批量删除员工基本信息
        return empMapper.deleteEmp(ids);
    }
    //根据id查询员工信息及工作经历
    @Override
    public Emp getEmpAndExpr(Integer id) {
       return empMapper.getEmpAndExpr(id);
    }

    //修改员工信息及工作经历
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateEmpAndExpr(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        //1.修改员工基本信息
        empMapper.updateEmp(emp);
        //2，根据员工id删除员工工作经历
        empExprMapper.deleteEmpExpr(Collections.singletonList(emp.getId()));
        //3.添加员工工作经历
        if(CollectionUtils.isEmpty(emp.getExprList())){
            emp.getExprList().forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.addEmpExpr(emp.getExprList());
        }

    }

}
